<?php

namespace App\Http\Controllers\Mini;

use App\Http\Controllers\Home\PaymentController;
use App\Models\BalanceLogs;
use App\Models\Configs;
use App\Models\Demands;
use App\Models\Feedbacks;
use App\Models\Mails;
use App\Models\Users;
use App\Models\UserLevels;
use App\Models\rewardOrder;
use App\Models\CashOuts;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use App\Http\Requests\Demand;
use App\Models\Validate;

class MyController extends Controller
{
    /**
     * 用户签到
     * @route api.user.userSignIn
     * @param user_id 用户id
     */
    public function userSignIn(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $user_info = Users::where('id',$user_id)->where('status','<>',-1)->first(['username','sign_in_at','type']);
            if (empty($user_info)) return response()->json(["code"=>0, "msg"=>'用户不存在']);

            $lists = [];
            $lists['is_sign'] = 0;//默认未签到
            if (trim(@date('Y-m-d', strtotime($user_info['sign_in_at']))) != trim(date('Y-m-d'))) {
                //签到送积分
                $integral = Configs::getConfig('integral');
                if($user_info['type'] == 1) {
                    $sign_in = $integral['hr_sign_in'];
                }else {
                    $sign_in = $integral['bus_login'];
                }
                Users::where('id',$user_id)->increment('integral',$sign_in);
                //添加日志记录
                $integral_arr = [
                    'user_id' => $user_id,
                    'user_name' => $user_info['username'],
                    'integral' => '+'.$sign_in,
                    'desc' => '签到送积分',
                    'type' => 1,
                ];
                IntegralLogs::create($integral_arr);
                $lists['integral'] = $sign_in;//签到赠送的积分
                $lists['is_sign'] = 1;//已签到
                Users::where('id',$user_id)->update(['sign_in_at' => date('Y-m-d H:i:s')]);

                return response()->json([
                    "code" => 1,
                    "msg" => "签到成功",
                    "data" => $lists
                ]);
            }else {
                return response()->json([
                    "code" => 1,
                    "msg" => "已签到",
                    "data" => $lists
                ]);
            }

        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 个人中心首页数据
     * @route api.user.userIndex
     * @param user_id 用户id
     */
    public function userindex(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $fields = '*';
            $user_info = Users::where('id',$user_id)->where('status','<>',-1)->first($fields);
            if (empty($user_info)) return response()->json(["code"=>0, "msg"=>'用户不存在']);
			
            $user_info['leve_info'] = UserLevels::where("id",$user_info['grade'])->select("id","name","icon")->get();

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $user_info
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    //阅读协议
    public function setRead(Request $request){
    	try{
    		$user_id = (int)$request->post('user_id');
    		$key = (string)$request->post('key');
    		
    		$users = Users::getUserInfo(['id'=>$user_id]);
    		$users->$key = 1;
    		$users->save();
    	}catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }
   

    /**
     * 用户基本信息修改
     * @param master_position
     */
    public function userInfoEdit(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::getUserInfo(['id'=>$user_id]);
            if (empty($users)) return response()->json(["code"=>0, "msg"=>'用户不存在']);
            
           
            
            $true_name = (string)$request->post('true_name','');
            $mobile = (string)$request->post('mobile','');
            $IDcard = (string)$request->post('IDcard','');
            $city = (int)$request->post('city',0);
            $trade = (int)$request->post('trade',0);
            $type = (int)$request->post('type',1);
            $positive_face = (string)$request->post('positive_face','');
            $reverse_face = (string)$request->post('reverse_face','');
            $code =  (string)$request->post('code','');
            if($mobile == ""){
            	response()->json(["code"=>0, "msg"=>'手机号不能为空']);
            }
            
            if($type == 3){
            	//申请悬赏主
            	$users->status =1;
            	if($positive_face == ""){
            		response()->json(["code"=>0, "msg"=>'请上传身份证正面照']);
            	}
            	if($reverse_face == ""){
            		response()->json(["code"=>0, "msg"=>'请上传身份证反面照']);
            	}
            	 
            }
            
            if($type == 2||$type == 3){
            	//团长申请
            	$users->status =1;
            	if($true_name == ""){
            		response()->json(["code"=>0, "msg"=>'请输入真实姓名']);
            	}
            	
            	if($IDcard == ""){
            		response()->json(["code"=>0, "msg"=>'请输入身份证号码']);
            	}
            	if($city == 0){
            		response()->json(["code"=>0, "msg"=>'请选择居住城市']);
            	}
            	if($trade == 0){
            		response()->json(["code"=>0, "msg"=>'请选择行业']);
            	}
            	
            }
            
            if($users['mobile'] != $mobile){
            	//表示手机号不同
            	if($code == ''){
            		response()->json(["code"=>0, "msg"=>'请输入验证码']);
            	}else{
            		$info = Validate::where(['mobile'=>$mobile,'v_type'=>1])->first();
            		if((strtotime($info['created_at'])+30*60)<time()){
            			Validate::where(['mobile'=>$mobile,'v_type'=>1])->delete();
            			response()->json(["code"=>0, "msg"=>'验证码过期，请重新获取']);
            		}elseif($info['code'] != $code){
            			response()->json(["code"=>0, "msg"=>'验证码错误']);
            		}else{
            			$users->mobile = $mobile;
            			Validate::where(['mobile'=>$mobile,'v_type'=>1])->delete();
            		}
            	}
            }
        
            
           
            
            
            if((string)$request->post('avatar')){
            	$users->avatar = (string)$request->post('avatar');
            }
            if((string)$request->post('nickname')){
            	$users->nickname = (string)$request->post('nickname');
            }
            
            if($true_name){
            	$users->true_name = $true_name;
            }
            
            if($IDcard){
            	$users->IDcard = $IDcard;
            }
          	if($city){
          		$users->city = $city;
          	}
            if($type){
            	$users->type = $type;
            }
            if($trade){
            	$users->trade = $trade;
            }      
            if($positive_face){
            	$users->positive_face = $positive_face;
            }
            if($reverse_face){
            	$users->reverse_face = $reverse_face;
            }
            
            $users->save();
           
            return response()->json([
                "code" => 1,
                "msg" => "操作成功",
                "data" => $users
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    

    /**
     * 用户余额记录列表
     * @route api.user.userBalanceLogs
     * @param user_id 用户id
     * @param page 页码
     * @param limit 条数
     */
    public function userBalanceLogs(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where('id',$user_id)->where('status','<>',-1)->value('id');
            if (empty($users)) return response()->json(["code"=>0, "msg"=>'用户不存在']);
            
            $page = (int)$request->post('page',1);
            $limit = (int)$request->post('limit',5);

            $lists = BalanceLogs::select(\DB::raw("FROM_UNIXTIME(UNIX_TIMESTAMP(created_at),'%Y-%m-%d') as date ,GROUP_CONCAT(id) as ids"))
                ->where('user_id',$user_id)
                ->groupBy(\DB::raw("FROM_UNIXTIME(UNIX_TIMESTAMP(created_at),'%Y-%m-%d')"))
                ->orderBy("date","desc")->paginate($limit, null, null, $page);

            foreach ($lists as $key=>$val){
                $ids = explode(",", $val['ids']);
                $lists[$key]['list'] = BalanceLogs::allLists(['id'=>$ids], ['id','user_id','desc','balance','type','pay_state']);
                unset($val['ids']);
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    

    /**
     * 用户提现
     * @route api.user.userCashOut
     * @param user_id 用户id
     * @param amount 提现金额
     * @param bank_no 银行账户
     * @param bank_user 开户行姓名
     * @param phone 提现人手机号
     * @param bank_name 开户行
     */
    public function userCashOut(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $user_info = Users::where('id',$user_id)->where('status','<>',-1)->first(['id','type','amount','status','balance','IDcard','true_name','nickname']);
           
            if (empty($user_info)) return response()->json(["code"=>0, "msg"=>'用户不存在']);

            if($user_info['status'] == 1){
            	return response()->json(["code"=>0, "msg"=>'用户审核中，不能提现']);
            }
            if($user_info['status'] == 3){
            	return response()->json(["code"=>0, "msg"=>'审核未通过，不能提现']);
            }
            
            if($user_info["status"] ==4 ){
            	return response()->json(["code"=>0, "msg"=>'您已被拉入黑名单，无法提现']);
            }

            if($user_info['type'] < 3){
            	
            	
            	$info = CashOuts::where("user_id",$user_id)->whereDate('created_at','>=',date('Y-m-d H:i:s',time()-24*3600))->first('id');
            	if(!empty($info)){
            		return response()->json(["code"=>0, "msg"=>'一天只能提现一次']);
            	}
            }
     
            $amount = $request->post("amount");
            $bank_no = (string)$request->post("bank_no");
            $bank_name = (string)$request->post("bank_name");
            $phone = (string)$request->post("phone");
            $bank_user = (string)$request->post("bank_user");
            
            $paytype = (int)$request->post("paytype",1);
            $qrcode = (string)$request->post("qrcode","");
            $paycount = (string)$request->post("paycount","");
  
           
            if(!preg_match('/^((13|14|15|16|17|18|19)[0-9]\d{8})$/', $phone)){
                return response()->json(["code"=>0, "msg"=>'请填写正确的手机号码']);
            }
            //验证金额是否足够
            if ($amount < 30) {
            	
                return response()->json(["code"=>0, "msg"=>'提现金额不能低于30']);
            }
           
            if (floatval($user_info['balance']) < $amount) {
                return response()->json(["code"=>0, "msg"=>'余额不足']);
            }
            

            $data = [];
            
            $base = Configs::getConfig('base');
            
            $data['user_id'] = $user_id;
            $data['user_name'] = $user_info['true_name']?$user_info['true_name']:$user_info['nickname'];
            $data['phone'] = $phone;
            $data['amount'] = $amount*(100-$base['tx_rate'])/100;
            $data['useramount'] = $amount;
            $data['bank_name'] = $bank_name;
            $data['bank_no'] = $bank_no;
            $data['bank_user'] = $bank_user;
            
            $data['pay_type'] = $paytype;
            $data['qrcode'] = $qrcode;
            $data['paycount'] = $paycount;
           
            $insert = CashOuts::create($data);
            if (!$insert) {
                return response()->json(["code"=>0, "msg"=>'提现申请发起失败']);
            }
            Users::where('id',$user_id)->where('status','<>',-1)->decrement('balance',$amount);
            
            
            
            return response()->json(["code"=>1, "msg"=>'提现申请已发起，我们会尽快处理，请耐心等待']);
            
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    public function getCashInfo(Request $request){
    		$user_id = (int)$request->post('user_id');
    		if($user_id>0){
    			$uinfo = CashOuts::where('user_id',$user_id)->orderBy('created_at','desc')->first();
    			return response()->json(["code"=>0, "msg"=>'','data'=>$uinfo]);
    		}else{
    			return response()->json(["code"=>1, "msg"=>'没有记录','data'=>'']);
    		}	
    }
    
    /**
     * 用户站内消息列表
     * @route api.user.userMailsLists
     * @param user_id 用户id
     * @param page 页码
     * @param limit 条数
     * @param status 类型 1:未读 2:已读
     */
    public function userMailsLists(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where('id',$user_id)->where('status','<>',-1)->value('id');
            if (empty($users)) return response()->json(["code"=>0, "msg"=>'用户不存在']);

            $page = (int)$request->post('page',1);
            $limit = (int)$request->post('limit',5);
            $status = (int)$request->post('status');//类型 1:未读 2:已读

            $params['user_id'] = $user_id;
            $params['status'] = $status;
            $lists = Mails::select(\DB::raw("FROM_UNIXTIME(UNIX_TIMESTAMP(created_at),'%Y-%m-%d') as date ,GROUP_CONCAT(id) as ids"))
                ->where(function ($query) use ($params) {
                    if(isset($params['user_id']) && $params['user_id']) {
                        $query ->where('user_id',$params['user_id']);
                    }
                    if(isset($params['status']) && $params['status']) {
                        $query ->where('status',$params['status']);
                    }
                })->where('status','<>',-1)
                ->groupBy(\DB::raw("FROM_UNIXTIME(UNIX_TIMESTAMP(created_at),'%Y-%m-%d')"))
                ->orderBy("date","desc")->paginate($limit, null, null, $page);
            foreach ($lists as $key=>$val){
                $ids = explode(",", $val['ids']);
                $lists[$key]['list'] = Mails::allLists(['id'=>$ids], ['id','title','user_id','status']);
                unset($val['ids']);
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户站内消息详情
     * @route api.user.userMailsDetails
     * @param user_id 用户id
     * @param maile_id 消息id
     */
    public function userMailsDetails(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where('id',$user_id)->where('status','<>',-1)->value('id');
            if (empty($users)) return response()->json(["code"=>0, "msg"=>'用户不存在']);


            $maile_id = (int)$request->post('maile_id');//消息id
            if (empty($maile_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);

            $lists = Mails::details(['id'=>$maile_id,'user_id'=>$user_id], $fields=['*']);
            Mails::where('id',$maile_id)->update(['status'=>2]);//变为已读

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户站内消息标记为已读
     * @route api.user.userMailsRead
     * @param user_id 用户id
     * @param maile_id 消息id(字符串：逗号隔开)
     */
    public function userMailsRead(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where('id',$user_id)->where('status','<>',-1)->value('id');
            if (empty($users)) return response()->json(["code"=>0, "msg"=>'用户不存在']);

            $maile_id = $request->post('maile_id');//消息id
            if (empty($maile_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $ids = explode(',',$maile_id);

            Mails::where('user_id',$user_id)->whereIn('id',$ids)->update(['status'=>2]);//变为已读

            return response()->json(["code"=>1, "msg"=>'操作成功']);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户站内消息删除
     * @route api.user.userMailsDelete
     * @param user_id 用户id
     * @param maile_id 消息id(字符串：逗号隔开)
     */
    public function userMailsDelete(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where('id',$user_id)->where('status','<>',-1)->value('id');
            if (empty($users)) return response()->json(["code"=>0, "msg"=>'用户不存在']);

            $maile_id = $request->post('maile_id');//消息id
            if (empty($maile_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $ids = explode(',',$maile_id);

            Mails::where('user_id',$user_id)->whereIn('id',$ids)->update(['status'=>-1]);//软删除

            return response()->json(["code"=>1, "msg"=>'删除成功']);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户投诉建议列表
     * @route api.user.userFeedbacksLists
     * @param user_id 用户id
     * @param page 页码
     * @param limit 条数
     * @param isreply 类型 1:未读 2:已读
     */
    public function userFeedbacksLists(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where('id',$user_id)->where('status','<>',-1)->value('id');
            if (empty($users)) return response()->json(["code"=>0, "msg"=>'用户不存在']);

            $page = (int)$request->post('page',1);
            $limit = (int)$request->post('limit',5);
            $isreply = (int)$request->post('isreply');//类型 1:未读 2:已读

            $params['user_id'] = $user_id;
            $params['isreply'] = $isreply;
            $lists = Feedbacks::select(\DB::raw("FROM_UNIXTIME(UNIX_TIMESTAMP(created_at),'%Y-%m-%d') as date ,GROUP_CONCAT(id) as ids"))
                ->where(function ($query) use ($params) {
                    if(isset($params['user_id']) && $params['user_id']) {
                        $query ->where('user_id',$params['user_id']);
                    }
                    if(isset($params['isreply']) && $params['isreply']) {
                        $query ->where('isreply',$params['isreply']);
                    }
                })->where('status','<>',-1)
                ->groupBy(\DB::raw("FROM_UNIXTIME(UNIX_TIMESTAMP(created_at),'%Y-%m-%d')"))
                ->orderBy("date","desc")->paginate($limit, null, null, $page);
            foreach ($lists as $key=>$val){
                $ids = explode(",", $val['ids']);
                $lists[$key]['list'] = Feedbacks::allLists(['id'=>$ids], ['id','content','user_id','isreply']);
                unset($val['ids']);
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户投诉建议详情
     * @route api.user.userFeedbacksDetails
     * @param user_id 用户id
     * @param feed_id 建议id
     */
    public function userFeedbacksDetails(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where('id',$user_id)->where('status','<>',-1)->value('id');
            if (empty($users)) return response()->json(["code"=>0, "msg"=>'用户不存在']);

            $feed_id = (int)$request->post('feed_id');//建议id
            if (empty($feed_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);

            $lists = Feedbacks::details(['id'=>$feed_id,'user_id'=>$user_id], $fields=['*']);

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户投诉建议添加
     * @route api.user.userFeedbacksAdd
     * @param user_id 用户id
     * @param content 内容
     * @param images 图片
     */
    public function userFeedbacksAdd(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where('id',$user_id)->where('status','<>',-1)->first(['true_name','nickname']);
            if (empty($users)) return response()->json(["code"=>0, "msg"=>'用户不存在']);
			$reward_id = (int)$request->post('reward_id');
			if (empty($reward_id)) return response()->json(["code"=>0, "msg"=>'任务参数错误']);
			$order_id = (int)$request->post('order_id');
			if (empty($order_id)) return response()->json(["code"=>0, "msg"=>'报名参数错误']);
            $images = (string)$request->post('images');
            if (!empty($images)){
                $images = explode(',',$images);
            }

            $params = [
                'user_id' => $user_id,
                'user_name' => $users['ture_name']?$users['ture_name']:$users['nickname'],
            	'reward_id' => $reward_id,
            	'order_id' => $order_id,
                'content' => (string)$request->post('content'),
                'images' => $images,
            	'status'=>1,	
                'created_at' => date('Y-m-d H:i:s'),
            ];
            Feedbacks::create($params);
		//	rewardOrder::where(array('order_id'=>$order_id))->
            
            return response()->json(["code"=>1, "msg"=>'申述已提交，我们会尽快处理']);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户投诉建议删除
     * @route api.user.userFeedbacksDelete
     * @param user_id 用户id
     * @param feed_id 建议id(字符串：逗号隔开)
     */
    public function userFeedbacksDelete(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where('id',$user_id)->where('status','<>',-1)->value('id');
            if (empty($users)) return response()->json(["code"=>0, "msg"=>'用户不存在']);

            $feed_id = $request->post('feed_id');//建议id
            if (empty($feed_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $ids = explode(',',$feed_id);

            Feedbacks::where('user_id',$user_id)->whereIn('id',$ids)->update(['status'=>-1]);//删除

            return response()->json(["code"=>1, "msg"=>'删除成功']);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户修改密码
     * @route api.user.userChangePwd
     * @param user_id 用户id
     * @param mobile 手机号
     * @param password 新密码
     * @param confirmc_pwd 确认密码
     */
    public function userChangePwd (Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where('id',$user_id)->where('status','<>',-1)->value('id');
            if (empty($users)) return response()->json(["code"=>0, "msg"=>'用户不存在']);

            $mobile = (string)$request->post('mobile');
            $password = (string)$request->post('password');
            $confirmc_pwd = (string)$request->post('confirmc_pwd');
            if(empty($mobile) || empty($password) || empty($confirmc_pwd)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            if(!preg_match('/^((13|14|15|16|17|18)[0-9]\d{8})$/', $mobile)) return response()->json(["code"=>0, "msg"=>'请填写正确的手机号码']);
            if($password !== $confirmc_pwd){
                return response()->json(["code"=>0, "msg"=>'两次密码输入不一致,请重新输入']);
            }

            $info = Users::where(['id'=>$user_id,'mobile'=>$mobile])->where('status','<>',-1)->first();
            if(!empty($info)){
                $info->mobile = $mobile;
                $info->password = bcrypt($password);
                $info->save();

                return response()->json(["code"=>1, "msg"=>'修改成功,请重新登录']);
            }else{
                return response()->json(["code"=>0, "msg"=>'该用户不存在']);
            }
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 用户修改手机号
     * @route api.user.userChangeMobile
     * @param user_id 用户id
     * @param old_mobile 原手机号
     * @param new_mobile 新手机号
     * @return bool
     */
    public function userChangeMobile(Request $request)
    {
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where('id',$user_id)->where('status','<>',-1)->value('id');
            if (empty($users)) return response()->json(["code"=>0, "msg"=>'用户不存在']);

            $old_mobile = (string)$request->post('old_mobile');
            $new_mobile = (string)$request->post('new_mobile');
            if(empty($old_mobile) || empty($new_mobile)) return response()->json(["code"=>0, "msg"=>'原手机号或新手机号不能为空']);
            $str = '/^((13|14|15|16|17|18)[0-9]\d{8})$/';
            if(!preg_match($str, $old_mobile) || !preg_match($str, $new_mobile)){
                return response()->json(["code"=>0, "msg"=>'请填写正确的手机号码']);
            }
            if($old_mobile == $new_mobile){
                return response()->json(["code"=>0, "msg"=>'新手机号和原手机号相同，无需修改']);
            }
            $info = Users::where(['id'=>$user_id,'mobile'=>$old_mobile])->where('status','<>',-1)->first();
            if(!empty($info)){
                $info->mobile = $new_mobile;
                $info->save();
                return response()->json(["code"=>1, "msg"=>'修改成功,请重新登录']);
            }else{
                return response()->json(["code"=>0, "msg"=>'该用户不存在']);
            }
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * B端我的任务
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function myDemandLists(Request $request){
    	try {
    		$user_id = (int)$request->post('user_id');
    		if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
    		$users = Users::where('id',$user_id)->where('status','<>',-1)->value('type');
    		
    		$page = (int)$request->post('page',1);//页码
    		$limit = (int)$request->post('limit',10);//条数
    		$params = [   		
    			'user_id'=>(int)$request->post('user_id',0)//用户ID     		  				
    		];   		
    		$state = (int)$request->post('status');
    		if($state >= 1){
    			$params['status'] = $state;
    		}
    		   		
    		$sort = $request->post('sort','created_at');   //排序字段
    		
    		$sort_by =  $request->post('sort_by','desc'); //发布时间排序  asc 升序，desc 降序
    		
    		
    		$fields = ['id','title','price','ownnumber','number','start_at','end_at','created_at','content','view','area','unit','cate_id','pttype_id','cate_pid'];
    		$lists = Demands::allLists($params, $fields, $page, $limit, $sort, $sort_by);
    		$base = Configs::getConfig('base');
    		
    		foreach ($lists as $key=>$val){
    			$lists[$key]['start_at'] = trim(@date('m-d', strtotime($val['created_at'])));
    			$lists[$key]['end_at'] = trim(@date('m-d', strtotime($val['end_at'])));
    			$lists[$key]['price'] = floatval($val['price']*$base['price_rate']/100);  //任务报酬要扣除平台费用
    			$map = [
    				'reward_id'=>$val['id'],
    				'status'=>2,
    				'check_status'=>0
    			];
    			$lists[$key]['needchecknum'] = rewardOrder::where($map)->count("id");
    			$map1 = [
    					'reward_id'=>$val['id'],
    					'status'=>1
    			];
    			$lists[$key]['signnum'] = rewardOrder::where($map1)->count("id");
    		}
    		
    		return response()->json([
    				"code" => 1,
    				"msg" => "获取成功",
    				"data" => $lists
    		]);
    		
    	}catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }
    
    /**
     * 用户需求列表
     * @route api.user.userDemandLists
     * @param user_id 用户id
     * @param page 页码
     * @param limit 条数
     * @param state 状态 1:招标中 2:已完成 不传或其他：全部
     */
    public function userDemandLists(Request $request){
        try {

            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $users = Users::where('id',$user_id)->where('status','<>',-1)->value('type');
            if (empty($users)) return response()->json(["code"=>0, "msg"=>'用户不存在']);

            $page = (int)$request->post('page',1);
            $limit = (int)$request->post('limit',5);
            $state = (int)$request->post('state',0);  //1、进行中  2、申述中   3、未完成  4、已完成

			if($state>0){
				
				$params['status'] = $state;
				
				
				
			}
            $check_status =  (int)$request->post('check_status',0);
            if($check_status>0){
            	  $params['check_status'] =$check_status;
            }
               
            $params['user_id'] = $user_id;
         
            $lists = rewardOrder::allLists($params, '*', $page, $limit);
            
            foreach ($lists as $key => $val){
                $lists[$key]['reward'] = Demands::details(array("id"=>$val['reward_id']));
                
            }

            return response()->json([
                "code" => 1,
                "msg" => "操作成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

	/**
	 * 我的团员
	 * @return \Illuminate\Http\JsonResponse
	 */  
    public function getMyteamMembers(Request $request){
    	try {
    		$user_id = (int)$request->post('user_id');
    		$page = (int)$request->post('page',1);
    		if (empty($user_id)) {
    			return response()->json(["code"=>0, "msg"=>'请先登录']);
    		}
    		$type = Users::where('id',$user_id)->where('status','<>',-1)->value('type');
    		if($type != 2){
    			return response()->json(["code"=>0, "msg"=>'请先申请成为团长']);
    		}
    		$users = Users::select('id','nickname','true_name','created_at')->where('inviter_id',$user_id)->where('status','<>',-1)->orderBy('created_at', 'desc')->paginate(10, null, null, $page);
    		foreach ($users as $k=>$v){
    			$users[$k]['add_time'] = date('Y-m-d',strtotime($v['created_at']));
    		}
    		return response()->json([
    				"code" => 1,
    				"msg" => "获取成功",
    				"data" => $users
    		]);
    		
    	}catch (\Exception $e){
    		return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
    	}
    }

    /**
     * 对象转换数组
     * @param $e StdClass对象实例
     * @return array|void
     */
    public function objectToArray($e)
    {
        $e = (array)$e;
        foreach ($e as $k => $v) {
            if (gettype($v) == 'resource') return;
            if (gettype($v) == 'object' || gettype($v) == 'array')
                $e[$k] = (array)$this->objectToArray($v);
        }
        return $e;
    }
    
    public function getFeedBackFromMe(Request $request){
    	try {
    		$user_id = (int)$request->post('user_id');
    		if (empty($user_id)) {
    			return response()->json(["code"=>0, "msg"=>'请先登录']);
    		}
    		$list = Demands::where('user_id',$user_id)->get();
    		$ids = [];
    		foreach ($list as $key=>$val){
    			array_push($ids, $val['id']);
    		}
    		
    		$feeds = Feedbacks::whereIn('reward_id',$ids)->get();
    		foreach ($feeds as $key=>$v){
	    		switch ($v['status']){
				case 2:
				 	$feeds[$key]['status_info'] = '申述通过';
				  	break;  
				case 3:
					 $feeds[$key]['status_info'] = '申述驳回';
				  	break;
				case 3:
				  	 $feeds[$key]['status_info'] = '申述驳回';
				  	 break;
				default:
					$feeds[$key]['status_info'] = '申述中';
					break;
				}
				$feeds[$key]['users'] = Users::where('id',$v['user_id'])->first(['nickname','avatar']);
				$feeds[$key]['title'] = Demands::where('id',$v['reward_id'])->value('title');
    		}
    		return response()->json([
    				"code" => 1,
    				"msg" => "获取成功",
    				"data" => $feeds
    		]);
    	}catch (\Exception $e){
    		return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
    	}
    }

}